package ca.unbc.cpsc672.fuzzy;

import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.TreeSet;

import ca.unbc.cpsc672.fuzzy.function.MembershipFunction;

/**
 * One fuzzy set, contains several membership functions
 * @author xi
 *
 */
public class FuzzySet {
	private HashMap<String, MembershipFunction> funcMap = new HashMap<>();
	private final String name;
	private double range;

	public FuzzySet(String name, double range) {
		this.name = name;
		this.range = range;
	}

	public void addFunction(MembershipFunction f) {
		funcMap.put(f.getLinguisticVariable(), f);
		f.setFuzzySet(this);
	}

	public double getRange() {
		return range;
	}

	public Collection<MembershipFunction> getAllMembershipFunction() {
		TreeSet<MembershipFunction> set = new TreeSet<>(
				new Comparator<MembershipFunction>() {

					@Override
					public int compare(MembershipFunction o1,
							MembershipFunction o2) {
						int ret = Double.compare(o1.getCenter(), o2.getCenter());
						if (ret != 0)
							return ret;
						else
							return o1.getLinguisticVariable().compareTo(
									o2.getLinguisticVariable());
					}
				});
		set.addAll(funcMap.values());
		return set;
	}

	public String getName() {
		return name;
	}

	public MembershipFunction getMembershipFunction(String name) {
		return funcMap.get(name);
	}

	public String toCSVString() {
		StringBuffer sb = new StringBuffer();
		for (MembershipFunction f : getAllMembershipFunction()) {
			sb.append(name).append(",");
			sb.append(range).append(",");
			sb.append(f.toCSVString()).append("\n");
		}
		return sb.toString();
	}

	public Collection<String> getAllLinguisticVariables() {
		LinkedList<String> ret = new LinkedList<>();
		for (MembershipFunction mf : getAllMembershipFunction())
			ret.add(mf.getLinguisticVariable());
		return ret;
	}
}
